package com.yyfax.pay.order.model.vo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import com.yyfax.framework.yyfax.enums.YesNoEnum;
import com.yyfax.pay.common.enums.PaymentEnum;
import com.yyfax.pay.config.model.po.MerchantPaymentPO;
import com.yyfax.pay.order.model.po.UserAuthPO;

/**
 * 用户鉴权信息<br>
 * 支付认证信息为有效
 * 
 * @author buyi
 * @date 2017-04-17 10:13:36
 * @since v1.0.0
 */
@SuppressWarnings("serial")
public class UserAuthVO extends UserAuthPO {

	private List<UserPaymentVO> userPaymentVOs;

	public UserAuthVO() {
		super();
		userPaymentVOs = new ArrayList<>();
	}

	public List<UserPaymentVO> getUserPaymentVOs() {
		return userPaymentVOs;
	}

	public void setUserPaymentVOs(List<UserPaymentVO> userPaymentVOs) {
		if (userPaymentVOs == null) {
			return;
		}

		this.userPaymentVOs = userPaymentVOs;
	}

	/**
	 * 获取指定的支付通道鉴权信息
	 * 
	 * @author buyi
	 * @date 2017-04-27 10:19:16
	 * @since v1.0.0
	 * @param paymentEnum
	 * @return
	 */
	public UserPaymentVO getUserPayment(PaymentEnum paymentEnum) {
		if (this.userPaymentVOs == null) {
			return null;
		}

		for (UserPaymentVO vo : this.userPaymentVOs) {
			if (StringUtils.equals(paymentEnum.getValue(), vo.getPaymentCode())) {
				return vo;
			}
		}

		return null;
	}

	public UserPaymentVO getUserPayment(List<MerchantPaymentPO> merchantPaymentPOs) {
		if (merchantPaymentPOs == null || merchantPaymentPOs.isEmpty()) {
			return null;
		}

		if (this.userPaymentVOs == null || this.userPaymentVOs.isEmpty()) {
			return null;
		}

		// 根据有效状态
		Collections.sort(merchantPaymentPOs, new Comparator<MerchantPaymentPO>() {
			@Override
			public int compare(MerchantPaymentPO object1, MerchantPaymentPO object2) {
				return ComparisonChain.start().compare(object1.getState(), object2.getState(), Ordering.natural().reverse())
						.compare(object1.getPriority(), object2.getPriority(), Ordering.natural().reverse()).result();
			}
		});

		for (MerchantPaymentPO merchantPaymentPO : merchantPaymentPOs) {
			if (!YesNoEnum.YES.isValue(merchantPaymentPO.getState())) { // 如果商户支付配置信息无效
				continue;
			}

			UserPaymentVO userPayment = getUserPayment(PaymentEnum.fromValue(merchantPaymentPO.getPaymentCode()));
			if (userPayment != null) {
				return userPayment;
			}
		}
		
		return null;
	}

}
